package tools;

import java.nio.charset.Charset;
import java.util.Arrays;
import java.util.Random;

import sun.misc.BASE64Encoder;

/**
 * Outils pour manipuler des chaines de caractères.
 * @author Guillaume Poças & Jean-François Augé
 */
public class StringUtils {

	public static String generateRandomString(int length) {
        String chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890!\"#$%&'()*+,-./:;<=>?@[\\]^_`{|}~"; 
        StringBuffer pass = new StringBuffer();
        for(int x=0;x<length;x++)   {
           int i = (int)Math.floor(Math.random() * (chars.length() -1));
           pass.append(chars.charAt(i));
        }
        return pass.toString();
	}
	
	public static String toBase64(byte[] tab) {
		BASE64Encoder e = new BASE64Encoder();
		return e.encode(tab);
	}

	public static String bytesToString(byte[] tab) {
		String out = "";

		for(byte b : tab)
			out = out.concat(String.valueOf(b)+" ");

		return out;
	}
	
	public static String bytesToStringWithoutSpaces(byte[] tab) {
		int tmp;
		StringBuilder sb = new StringBuilder();

		for(int i = 0; i < tab.length; i++){
			tmp = Integer.valueOf(tab[i]);
			sb = sb.append((char)tmp);
		}

		return sb.toString();
	}

	public static byte[] stringToBytes(String str) {
		String[] tab = str.split(" ");
		byte[] out = null;

		if(tab.length != 1){
			out = new byte[tab.length];
			for(int i=0; i<tab.length; i++){
				//System.out.println("i:"+i+" & vaut:"+tab[i]);
				out[i] = (byte) ((int) Integer.valueOf(tab[i]));
			}
		}
		else{
			out = new byte[str.length()];
			for(int i=0; i<str.length(); i++){
				//System.out.println("i:"+i+" & vaut:"+str.charAt(i)+"=>"+(int) Integer.valueOf(str.charAt(i)));
				out[i] = (byte) ((int) Integer.valueOf(str.charAt(i)));
			}
		}

		return out;
	}

	public static void main(String[] args) {
		System.out.println("default charset "+Charset.defaultCharset().toString());
		byte[] test = PasswordSecurity.sha256_2("admin", "aaaaaaaaaaaa");
		String b64 = StringUtils.toBase64(test);
		System.out.println(" >>> "+b64);
		
		String db = StringUtils.bytesToString(test);
		System.out.println(db);
		byte[] test2 = StringUtils.stringToBytes(db);
		//System.out.println(" >>> "+StringUtils.toBase64(test2));
		System.out.println(Arrays.equals(test, test2));
		
		char[] random = StringUtils.generateRandomString(16).toCharArray();
		for(int i = 0; i < random.length; i++)	System.out.print(random[i]);
		System.out.println();
		byte[] rdm = StringUtils.stringToBytes(StringUtils.generateRandomString(16));
		for(int i = 0; i < random.length; i++)	System.out.print(rdm[i]+" ");
	}

}
